#include "inc/administrator.h"
#include "ui_administrator.h"
#include "inc/zg291paradata.h"
#include <QMessageBox>
Administrator::Administrator(QSerialPort *serialPort,QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Administrator),
    serialPort(serialPort)
{
    ui->setupUi(this);
}

Administrator::~Administrator()
{
    delete ui;
}

void Administrator::on_pushButton_clicked()
{
    // 先更新全局变量
    TEMP_enabled = ui->TEMP->isChecked();
    HUM_enabled = ui->HUM->isChecked();
    PM1_0_enabled = ui->PM1_0->isChecked();
    PM2_5_enabled = ui->PM2_5->isChecked();
    PM10_enabled = ui->pm10->isChecked();
    TVOC_enabled = ui->tvoc->isChecked();
    BORD_enabled = ui->bord->isChecked();
    CH2O_enabled = ui->ch2o->isChecked();
    CO2_enabled = ui->co2->isChecked();
    PECU_enabled = ui->pecu->isChecked();

    // 寄存器地址与变量对应关系
    QVector<quint16> registers = {
        0x1a,   // TEMP
        0x25,   // HUM
        0x30,   // PM1_0
        0x3b,   // PM2_5
        0x46,   // PM10
        0x51,   // TVOC
        0x5c,   // BORD
        0x67,   // CH2O
        0x72,   // CO2
        0x7d    // PECU
    };

    QVector<bool*> variables = {
        &TEMP_enabled,
        &HUM_enabled,
        &PM1_0_enabled,
        &PM2_5_enabled,
        &PM10_enabled,
        &TVOC_enabled,
        &BORD_enabled,
        &CH2O_enabled,
        &CO2_enabled,
        &PECU_enabled
    };

    QStringList failedRegisters;
    bool allSuccess = true;

    // 从机地址和功能码
    const quint8 slaveAddress = 0x00;
    const quint8 functionCode = 0x06; // 写单个寄存器
    QByteArray response;
    // 遍历所有寄存器并写入
    for (int i = 0; i < registers.size(); ++i) {
        QByteArray request;
        quint16 value = *(variables[i]) ? 0x0001 : 0x0000; // 布尔值转为16位值

        // 构造Modbus请求帧
        request.append(slaveAddress);
        request.append(functionCode);
        request.append(static_cast<char>((registers[i] >> 8) & 0xFF)); // 寄存器地址高字节
        request.append(static_cast<char>(registers[i] & 0xFF));        // 寄存器地址低字节
        request.append(static_cast<char>((value >> 8) & 0xFF));       // 数据高字节
        request.append(static_cast<char>(value & 0xFF));              // 数据低字节

        // 计算CRC
        quint16 crc = calculateCRC(request);
        request.append(static_cast<char>(crc & 0xFF));     // CRC低字节
        request.append(static_cast<char>((crc >> 8) & 0xFF)); // CRC高字节

        // 发送请求
        serialPort->write(request);
        if (!serialPort->waitForBytesWritten(1000)) {
            failedRegisters << QString("0x%1").arg(registers[i], 0, 16);
            allSuccess = false;
            continue;
        }

        // 等待响应
        if (serialPort->waitForReadyRead(1000)) {
            QByteArray response = serialPort->readAll();
            while (serialPort->waitForReadyRead(10)) {
                response += serialPort->readAll();
            }

            // 验证响应
            if (response.size() != 8 ||response.at(1) != functionCode) {
                failedRegisters << QString("0x%1").arg(registers[i], 0, 16);
                allSuccess = false;
            }
        } else {
            failedRegisters << QString("0x%1").arg(registers[i], 0, 16);
            allSuccess = false;
        }
    }

    // 显示结果
    if (allSuccess) {
        QMessageBox::information(this, "成功", "所有寄存器写入成功！");
        emit admin_config_succeed();
    } else {
        QMessageBox::warning(this, "部分失败",
            QString("以下寄存器写入失败：\n%1").arg(failedRegisters.join("\n")));
    }
}
